import '@/utils/lodash-fix';
import _ from "@/npm/lodash/index";
import {
	ROCY_AI_HOST
} from './constant';
import {
	base_url,
	servicePost
} from './service';
import {
	isAnyEmpty
} from './util';
import {
	getImageExtName
} from './file';

export const EXTENSIONS = ["docx", "xlsx", "pdf", "txt", "csv", "md"]
const fs = wx.getFileSystemManager();

export const isPng = (path) => path.toLowerCase().endsWith(".png")

export async function convertPng2JPG(imagePath, imageInfo) {
	const {
		width,
		height
	} = imageInfo
	const canvas = wx.createOffscreenCanvas({
		type: '2d',
		width,
		height
	})
	const context = canvas.getContext('2d')
	const image = canvas.createImage()
	await new Promise(resolve => {
		image.onload = resolve
		image.src = imagePath
	})
	context.clearRect(0, 0, width, height)
	context.drawImage(image, 0, 0, width, height)
	return new Promise(resolve => {
		wx.canvasToTempFilePath({
			width,
			height,
			destWidth: width,
			destHeight: height,
			canvas,
			fileType: 'jpg',
			quality: 1,
			success(res) {
				resolve(res.tempFilePath)
			},
			fail() {
				resolve('')
			}
		})
		const imagePath = `${wx.env.USER_DATA_PATH}/temp-${Date.now()}.jpg`
		wx.getFileSystemManager().writeFile({
			filePath: imagePath,
			data: canvas.toDataURL('image/jpeg').replace(/^data:image\/\w+;base64,/, ''),
			encoding: 'base64',
			success() {
				resolve(imagePath)
			},
			fail() {
				resolve('')
			},
		})
	})
}

export function setImage(tempFile) {
	tempFile["size"] = (tempFile["size"] / 1024).toFixed(0)
	if (tempFile["size"] == 0) tempFile["size"] = 1
	tempFile["size"] = `${tempFile["size"]}K`
	const ext = _.lowerCase(_.last(_.split(tempFile["path"], ".")))
	if (EXTENSIONS.includes(ext)) tempFile["icon"] = `https://rocy-ai.wang/mp_images/${ext}.svg`
	return tempFile
}
export const getRemoteOnePicturePromise = (url) => new Promise((resolve, reject) => getRemoteOnePicture(url, (base64) => resolve(base64), e => reject(e)))
export function getRemoteOnePicture(url, callback, error) {
	servicePost("/word/get_remote_image_base64", (base64) => {
		if (_.isNil(base64)) error()
		else callback(base64)
	}, {
		image_url: url
	}, null, null, error)
}
export const selectLocalMultiPicturesPromise = () => new Promise((resolve) => {
	wx.chooseImage({
		sizeType: ['original'],
		sourceType: ['album', 'camera'],
		success: (res) => resolve(res.tempFiles)
	})
})
export function selectLocalMultiPicturesBase64(callback) {
	wx.chooseImage({
		sizeType: ['original'],
		sourceType: ['album', 'camera'],
		success: function (res) {
			var tempFiles = res.tempFiles;
			if (tempFiles.length > 0) {
				const base64Arr = []
				let count = 0
				_.forEach(tempFiles, ({
					path,
					size
				}, index) => getBase64(path, (base64) => {
					_.set(base64Arr, [index], base64)
					count += 1
					if (count === tempFiles.length) callback(tempFiles, base64Arr)
				}))
			}
		}
	})
}
export function selectLocalOnePicture(callback) {
	wx.chooseImage({
		count: 1,
		sizeType: ['original'],
		sourceType: ['album', 'camera'],
		success: function (res) {
			var tempFilePaths = res.tempFilePaths;
			if (tempFilePaths.length > 0) getBase64(tempFilePaths[0], callback)
		}
	})
}
export function getImageUrl(image) {
	return `${ROCY_AI_HOST}/mp_images/${image}`
}
export function downloadAndSaveVideo(url, name, callback, error) {
	const filePath = wx.env.USER_DATA_PATH + `/${name || "aa-mp.mp4"}`
	wx.downloadFile({
		url,
		filePath,
		success(res) {
			if (res.statusCode === 200) wx.saveVideoToPhotosAlbum({
				filePath,
				success: () => {
					callback && callback()
					wx.showToast({
						title: '保存成功',
					})
				},
				fail: () => error && error()

			})
		},
		fail: () => error && error()
	})
}
export function downloadAndSaveImage(url, name, callback) {
	const filePath = wx.env.USER_DATA_PATH + `/${name || "aa-mp.png"}`
	wx.downloadFile({
		url,
		filePath,
		success(res) {
			if (res.statusCode === 200) wx.saveImageToPhotosAlbum({
				filePath,
				success: () => {
					callback && callback()
					wx.showToast({
						title: '保存成功',
					})
				}
			})
		}
	})
}

export function saveImage(src, callback) {
	if (src.startsWith("http://tmp")) wx.saveImageToPhotosAlbum({
		filePath: src,
		success: () => {
			wx.showToast({
				title: '保存成功',
			})
			callback && callback()
		}
	})
	else if (src.startsWith("http")) downloadAndSaveImage(src, null, callback)
	else saveBase64Image(src, null, callback)
}
export const getBase64Promise = (imagePath) => new Promise((resolve, reject) => {
	function run(imagePathLocal) {
		fs.readFile({
			filePath: imagePathLocal,
			encoding: 'base64',
			success: (res) => resolve(res.data),
			fail: (err) => reject(null)
		});
	}
	if (isAnyEmpty(imagePath)) resolve(null)
	else if (imagePath.startsWith("http")) wx.downloadFile({
		url: imagePath,
		success(res) {
			if (res.statusCode === 200) run(res.tempFilePath)
		}
	})
	else run(imagePath)
})
export function getBase64(imagePath, callback) {
	function run(imagePathLocal) {
		fs.readFile({
			filePath: imagePathLocal,
			encoding: 'base64',
			success: function (res) {
				callback(res.data)
			},
			fail: function (err) {
				console.log("getBase64", err);
			}
		});
	}
	if (imagePath.startsWith("http")) wx.downloadFile({
		url: imagePath,
		success(res) {
			if (res.statusCode === 200) run(res.tempFilePath)
		}
	})
	else run(imagePath)

}
const BASE64_REGEX = /data:image\/(\w+);base64,/ig
export function isNotBase64Code(str) {
	return !isBase64Code(str)
}
export function isBase64Code(str) {
	try {
		atob(str)
		return /=+$/.test(str)
	} catch (e) {
		return false;
	}
}
export function getBase64Prefix(ext) {
	return `data:image/${ext||'png'};base64,`
}
export function matchBase64(v) {
	return BASE64_REGEX.test(v) ? RegExp.$1 : null
}
export function md5ToUrl(md5) {
	return `${base_url}/image/show?md5=${md5}`
}
export function addBase64Prefix(base64, ext) {
	if (isAnyEmpty(base64)) return null
	if (matchBase64(base64)) return base64
	if (isNotBase64Code(base64)) return base64
	return `${getBase64Prefix(ext)}${base64}`
}
export function removeBase64Prefix(base64) {
	if (matchBase64(base64)) return base64.replace(BASE64_REGEX, "")
	return base64
}

export function saveBase64Image(base64ImgUrl, name, callback) {
	const ext = getImageExtName(base64ImgUrl) || "png"
	const tmpPath = wx.env.USER_DATA_PATH + `/${name||`aa-mp.${ext}`}`
	wx.getFileSystemManager().writeFile({
		filePath: tmpPath,
		data: removeBase64Prefix(base64ImgUrl),
		encoding: 'base64',
		success: () => {
			wx.saveImageToPhotosAlbum({
				filePath: tmpPath,
				success: function () {
					callback && callback()
					wx.showToast({
						title: '保存成功',
					})
				},
				fail: function (e) {
					console.error(e)
					wx.showToast({
						title: '保存失败',
					})
				}
			})
		},
		fail: e => {
			console.error(e)
			wx.showToast({
				title: '保存失败',
			})
		}
	})
}

export const sample_base64 = ""